package com.blog.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.blog.mapper.MemberMapper;
import com.blog.mapper.RoleMapper;
import com.blog.mapper.TechniqueMapper;
import com.blog.model.Page;
import com.blog.model.ResultJSON;
import com.blog.model.TableJson;
import com.blog.pojo.Member;
import com.blog.pojo.Role;
import com.blog.pojo.Technique;
import com.blog.service.MemberService;


/** 
 * @author ant 
 * @date 创建时间：2017年6月15日 上午10:25:26  
 */
@Service
public class MemberServiceImpl implements MemberService {

	@Autowired
	private MemberMapper memberMapper;
	
	@Autowired
	private  RoleMapper roleMapper;
	
	@Autowired
	private TechniqueMapper techniqueMapper;
	
	@Override
	public Member findMemberByLoginName(String username) {
		Member member = memberMapper.getMemberByUserName(username);
		List<Role> roles = new ArrayList<>();
		for (Role role : member.getRoleList()) {
			Role findRole = roleMapper.selectByPrimaryKey(role.getRoleId());
			roles.add(findRole);
		}
		for (Role role : roles) {
			System.out.println(role.getPermissionList().size());
		}
		member.setRoleList(roles);
		return member;
	}

	@Override
	public Member findMemberByMemberId(Integer memberId) {
		Member member = memberMapper.selectByPrimaryKey(memberId);
		return member;
	}

	@Override
	public TableJson getTechniqueList(Technique technique, Page page) {
		TableJson json  = new TableJson();
		try {			
			List<Technique> techniqueList = techniqueMapper.selectByExample(technique,page);
			int total = techniqueMapper.countByExample(technique);				
			json.setRows(techniqueList);
			json.setTotal(total);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}

	@Override
	public Technique getTechniqueByTechniqueId(Integer techniqueId) {
		Technique technique = techniqueMapper.selectByPrimaryKey(techniqueId);
		return technique;
	}

	@Override
	public ResultJSON editTechnique(String act, Technique technique) {
		ResultJSON json = new ResultJSON();
		try {
			technique.setUpdateTime(new Date());
			if (StringUtils.equals(act, "edit")) {
				int i = techniqueMapper.update(technique);
				if (i > 0) {
					json.setSuccess(true);
					json.setMessage("更新个人技能成功");
				} else {
					json.setSuccess(false);
					json.setMessage("更新个人技能失败");
				}
			} else {
				technique.setCreateTime(new Date());
			    int i = techniqueMapper.insert(technique);
			    if (i > 0) {
					json.setSuccess(true);
					json.setMessage("添加个人技能成功");
				} else {
					json.setSuccess(false);
					json.setMessage("添加个人技能失败");
				}
			}
		} catch (Exception e) {
			json.setSuccess(false);
			json.setMessage("更新个人技能错误");
			e.printStackTrace();
		}
		return json;
	}

	

}
